<?php


namespace Xp130\Rank;
class ConfigLoader
{
    protected string $defaultConfigPath;
    protected string $projectRoot;

    public function __construct(string $configName = 'rank')
    {
        $this->defaultConfigPath = __DIR__ . '/../config/' . $configName . '.php';
        $this->projectRoot = $this->detectProjectRoot();
    }

    protected function detectProjectRoot(): string
    {
        // 尝试检测项目根目录，可以通过查找 composer.json 或其他标志文件
        $dir = getcwd();
        while ($dir !== '/' && !file_exists($dir . '/composer.json')) {
            $dir = dirname($dir);
        }

        return $dir === '/' ? '' : $dir;
    }

    public function load(): array
    {
        $configPaths = [
            $this->projectRoot . '/../config/autoload/rank.php', // 项目根目录下的配置文件
            $this->defaultConfigPath,                         // 组件自带的默认配置文件
        ];

        foreach ($configPaths as $path) {
            if (file_exists($path)) {
                return require $path;
            }
        }

        throw new \RuntimeException('Configuration file not found.');
    }
}